<template>
  <div class="rate-calculation">
    <h2 class="calculation-title">利率计算</h2>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="left"
      v-loading="loading"
      class="calculation-form"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="amount" label="票面金额">
            <el-input-number
              v-model="formData.amount"
              :min="0"
              :precision="2"
              placeholder="请输入票面金额"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="maturity_date" label="到期日">
            <el-date-picker
              v-model="formData.maturity_date"
              type="date"
              placeholder="请选择到期日"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="bank" label="承兑行">
            <el-autocomplete
              v-model="formData.bank"
              :fetch-suggestions="queryBankAsync"
              placeholder="请输入搜索承兑行"
              @select="handleBankSelect"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="handleQuery" :loading="loading">
          <el-icon><Search /></el-icon>
          计算利率
        </el-button>
        <el-button @click="resetForm">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 查询结果展示 -->
    <div v-if="queryResult" class="query-result">
      <el-divider content-position="left">计算结果</el-divider>
      <el-card class="result-card">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="票面金额" label-class-name="result-label">
            <span class="result-value">¥{{ formatNumber(queryResult.amount) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="到期日" label-class-name="result-label">
            <span class="result-value">{{ queryResult.maturity_date }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="承兑行" label-class-name="result-label">
            <span class="result-value">{{ queryResult.bank }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="每十万价格" label-class-name="result-label">
            <span class="result-value">{{ queryResult.price_per_hundred_thousand }}</span>
          </el-descriptions-item>
          <!-- <el-descriptions-item label="利率值" label-class-name="result-label">
            <span class="result-value rate-highlight">
              <span v-if="queryResult.rate_mode === 'FIXED'">{{ queryResult.rate }}%</span>
              <span v-else-if="queryResult.rate_mode === 'FLOAT'">{{ queryResult.rate }}%</span>
              <span v-else-if="queryResult.rate_mode === 'FIXED_AMOUNT'">¥{{ formatNumber(queryResult.rate) }}</span>
              <span v-else>{{ queryResult.rate }}</span>
            </span>
          </el-descriptions-item> -->
          <el-descriptions-item label="贴现费" label-class-name="result-label">
            <span class="result-value interest-highlight"
              >¥{{ formatNumber(queryResult.total_interest) }} ({{ formatNumber(queryResult.base_interest) }} +
              {{ formatNumber(queryResult.extra_interest) }})</span
            >
          </el-descriptions-item>
          <el-descriptions-item label="贴现金额" label-class-name="result-label">
            <span class="result-value amount-highlight">¥{{ formatNumber(queryResult.discount_amount) }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty description="请输入计算参数并点击计算利率按钮">
        <template #image>
          <el-icon size="60" color="#c0c4cc"><Calculator /></el-icon>
        </template>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue"
import { calcRatesApi, getBankssearchApi } from "@/api/calculator"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import { Search, Refresh } from "@element-plus/icons-vue"

const formRef = ref<FormInstance | null>(null)
const loading = ref<boolean>(false)
const queryResult = ref<any>(null)

const formData = reactive({
  amount: 0,
  maturity_date: "",
  bank: ""
})

const formRules: FormRules = reactive({
  amount: [
    { required: true, trigger: "blur", message: "请输入票面金额" },
    { type: "number", min: 0.01, trigger: "blur", message: "票面金额必须大于0" }
  ],
  maturity_date: [{ required: true, trigger: "blur", message: "请选择到期日" }],
  bank: [{ required: true, trigger: "blur", message: "请选择承兑行" }]
})

// 银行搜索相关
const queryBankAsync = (queryString: string, cb: (suggestions: any[]) => void) => {
  if (queryString) {
    getBankssearchApi({ bank_name: queryString })
      .then((res: any) => {
        const suggestions = res.data.data.map((bank: any) => ({
          value: bank.bank_name,
          id: bank.bank_id,
          ...bank
        }))
        cb(suggestions)
      })
      .catch(() => {
        cb([])
      })
  } else {
    cb([])
  }
}

const handleBankSelect = (item: any) => {
  formData.bank = item.value
}

// 重置表单
const resetForm = () => {
  formData.amount = 0
  formData.maturity_date = ""
  formData.bank = ""
  queryResult.value = null
  formRef.value?.resetFields()
}

// 执行查询
const handleQuery = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      calcRatesApi({
        amount: formData.amount,
        maturity_date: formData.maturity_date,
        bank: formData.bank
      })
        .then((res: any) => {
          queryResult.value = res.data
          ElMessage.success("计算成功")
        })
        .catch((error) => {
          ElMessage.error("计算失败：" + (error.message || "未知错误"))
          queryResult.value = null
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

// 格式化数字显示
const formatNumber = (num: number | string) => {
  const number = typeof num === "string" ? parseFloat(num) : num
  return number.toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}
</script>

<style scoped>
.rate-calculation {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.calculation-title {
  margin: 0 0 24px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.calculation-form {
  margin-bottom: 24px;
}

.query-result {
  margin-top: 24px;
}

.result-card {
  margin-top: 16px;
}

.result-value {
  font-weight: 600;
  color: #303133;
}

.rate-highlight {
  color: #409eff;
  font-size: 16px;
}

.interest-highlight {
  color: #f56c6c;
  font-size: 16px;
}

.amount-highlight {
  color: #67c23a;
  font-size: 16px;
}

.empty-state {
  margin-top: 40px;
  text-align: center;
}

:deep(.result-label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-descriptions__label) {
  background-color: #f8f9fa;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-button) {
  margin-right: 12px;
}

:deep(.el-button:last-child) {
  margin-right: 0;
}
</style>
